package com.dff.jrfw;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.hardware.fingerprint.FingerprintManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;

import com.dff.jrfw.common.Constant;
import com.dff.jrfw.databinding.ActivityMainBinding;
import com.dff.jrfw.dialog.BiometricIdentifyDialog;
import com.dff.jrfw.dialog.ScanLoginDialog;
import com.dff.jrfw.jsbridge.BrowserChromeClient;
import com.dff.jrfw.jsbridge.BrowserClient;
import com.dff.jrfw.model.QueryDeviceInfoModel;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtils;
import com.dff.jrfw.remote.RetrofitUtilsTwo;
import com.dff.jrfw.requestBody.QrCodeDto;
import com.dff.jrfw.service.WebPreloadService;
import com.dff.jrfw.utils.DeviceIdUtil;
import com.dff.jrfw.utils.DpUtils;
import com.dff.jrfw.utils.GsonUtils;
import com.dff.jrfw.utils.SharedPreferenceUtils;
import com.dff.jrfw.utils.ShowFileUtil;
import com.dff.jrfw.utils.ToastUtil;
import com.gyf.immersionbar.ImmersionBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import cn.com.infosec.mobile.android.managers.CertManager;
import cn.com.infosec.mobile.android.managers.SignManager;
import cn.com.infosec.mobile.android.result.Result;
import cn.jpush.android.api.JPushInterface;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private ActivityMainBinding binding;
    private File tmpDir;
    private boolean isPreloadTimeout = true;

    public static void callMe(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("ttt", "onResume");
        ActivityManager.getInstance().clearStackIfNotTop();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("ttt", "onCreate");
        String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
        JPushInterface.setAlias(getApplicationContext(), 0, Constant.CUST_CODE + curLoginAccount);
        ImmersionBar.with(this)
                .reset()
                .barEnable(true)
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                .init();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initView();
        tmpDir = new File(getCacheDir(), "tmp");
        if (!tmpDir.exists()) {
            tmpDir.mkdirs();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_click_again:
                binding.webView.reload();
                break;
        }
    }

    private int offset = 0;

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        Log.d("ttt", "initView");
        binding.tvClickAgain.setOnClickListener(this);
        BrowserClient browserClient = new BrowserClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showLoading();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                hideLoading();
                Log.d("ttt", "onPageFinished");
                String content = getIntent().getStringExtra("content");
                if (content != null) {
                    Log.d("ttt", "推送参数:" + content);
                    view.loadUrl("javascript:JSBridge._native_call_web('goMessageCenter')");
                }
            }
        };
        registerFunction(browserClient);
        WebSettings webSettings = binding.webView.getSettings();
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setJavaScriptEnabled(true);
        binding.webView.setWebViewClient(browserClient);
        binding.webView.setWebChromeClient(new BrowserChromeClient());
        binding.webView.setHorizontalScrollBarEnabled(false);
        binding.webView.setVerticalScrollBarEnabled(false);
        binding.rlWebView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect rect = new Rect();
            binding.rlWebView.getWindowVisibleDisplayFrame(rect);
            if (offset == 0 && rect.bottom < binding.rlWebView.getBottom()) {
                browserClient.queryFocus(binding.webView, percent -> {
                    int bottom = (int) (percent * binding.webView.getHeight());
                    if (rect.bottom < bottom) {
//                        offset = rect.bottom - bottom;
                        offset = rect.bottom - binding.rlWebView.getHeight();
                        Log.d("xxx", "移动" + offset);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.webView.getLayoutParams();
                        layoutParams.topMargin = offset;
                        binding.webView.setLayoutParams(layoutParams);
                        binding.webView.requestLayout();
                        binding.rlWebView.setPadding(0, 0, 0, -offset);
                    }
                });
            } else if (offset != 0 && rect.bottom > binding.webView.getBottom()) {
                Log.d("xxx", "还原");
                offset = 0;
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.webView.getLayoutParams();
                layoutParams.topMargin = 0;
                binding.webView.requestLayout();
                binding.webView.setLayoutParams(layoutParams);
                binding.rlWebView.setPadding(0, 0, 0, 0);
            }
        });
        binding.webView.loadUrl(Constant.APP_H5);
    }


    private void registerFunction(BrowserClient browserClient) {
        browserClient.registerHandler("rotateBegin", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        });
        browserClient.registerHandler("rotateEnd", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });

        browserClient.registerHandler("version", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                VersionActivity.callMe(MainActivity.this);
            }
        });

        browserClient.registerHandler("show", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String name = jsonObject.optString("name");
                    String type = jsonObject.optString("type");
                    if (TextUtils.isEmpty(name)) {
                        return;
                    }
                    if (TextUtils.isEmpty(type)) {
                        ShowFileUtil.openFile(MainActivity.this, new File(tmpDir, name).getPath());
                    } else {
                        File file = new File(getCacheDir(), name);
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction(Intent.ACTION_VIEW);
                        Uri uri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileProvider", file);
                            //添加这一句表示对目标应用临时授权该Uri所代表的文件
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        } else {
                            uri = Uri.fromFile(file);
                        }
                        intent.setDataAndType(uri, type);
                        startActivity(intent);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        browserClient.registerHandler("background", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                moveTaskToBack(false);
            }
        });

        browserClient.registerHandler("transition", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String name = jsonObject.optString("name");
                    long offset = jsonObject.optInt("offset");
                    long length = jsonObject.optInt("length");
                    String hexString = jsonObject.optString("data");
                    ByteBuffer buffer = ByteBuffer.allocate(hexString.length() / 2);
                    for (int i = 0; i < hexString.length(); i++) {
                        String hexStr = hexString.charAt(i) + "";
                        i++;
                        hexStr += hexString.charAt(i);
                        byte b = (byte) Integer.parseInt(hexStr, 16);
                        buffer.put(b);
                    }
                    byte[] binary = buffer.array();
                    File file = new File(tmpDir, name);
                    if (offset == 0) {
                        clear(tmpDir);
                    }
                    if (binary.length == length) {
                        RandomAccessFile randomAccessFile = null;
                        try {
                            randomAccessFile = new RandomAccessFile(file, "rw");
                            randomAccessFile.seek(offset);
                            randomAccessFile.write(binary);
                            callback.callback(String.valueOf(offset + length));
                        } catch (IOException e) {
                            e.printStackTrace();
                            callback.callback("-3");
                        } finally {
                            if (randomAccessFile != null) {
                                try {
                                    randomAccessFile.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        callback.callback("-4");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    callback.callback("-1");
                }
            }
        });
        browserClient.registerHandler("getStatusBarHeight", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                int navigationBarHeight = DpUtils.getStatusBarHeight(MainActivity.this);
                int screenHeight = DpUtils.getScreenHeight(MainActivity.this);
                callback.callback(String.format(Locale.getDefault(), "%.2f", navigationBarHeight * 100f / screenHeight));
            }
        });

        browserClient.registerHandler("getToken", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                String token = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.TOKEN, "");
                callback.callback(token);
            }
        });

        browserClient.registerHandler("getUserInfo", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
                getUserBaseInfo(curLoginAccount, callback);
            }
        });

        browserClient.registerHandler("detachSign", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String pwd = jsonObject.optString("pwd");
                    String plainText = jsonObject.optString("plainText");
                    String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
                    sign(1, curLoginAccount, pwd, plainText, callback);
                } catch (JSONException e) {
                    callback.callback(e.getMessage());
                    e.printStackTrace();
                }
            }
        });

        browserClient.registerHandler("modifyLoginPsd", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                ModifyLoginPsdActivity.callMe(MainActivity.this);
            }
        });

        browserClient.registerHandler("modifyPayPsd", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                ModifyPayPsdActivity.callMe(MainActivity.this);
            }
        });

        browserClient.registerHandler("biometricIdentifySetting", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                BiometricIdentifyActivity.callMe(MainActivity.this);
            }
        });

        browserClient.registerHandler("scanQRCodeLogin", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                callback.callback("request response for " + data);
                ScannerActivity.callMe(MainActivity.this, 0);
            }
        });

        browserClient.registerHandler("safeQuit", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                callback.callback("request response for " + data);
                AccountLogoutActivity.callMe(MainActivity.this);
            }
        });

        browserClient.registerHandler("isBiometricIdentifyEnable", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                try {
                    JSONObject json = new JSONObject(data);
                    if (supportFingerprint()) {
                        String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
                        if (curLoginAccount != null) {
                            getBioState(curLoginAccount, callback);
                        } else {
                            try {
                                json.put("code", 0);
                                json.put("msg", "获取当前用户名失败");
                                callback.callback(json.toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        json.put("code", 0);
                        json.put("msg", "您的设备不支持指纹");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        browserClient.registerHandler("biometricIdentify", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    try {
                        JSONObject json = new JSONObject(data);
                        int type = json.optInt("type");
                        switch (type) {
                            case 0:
                                try {
                                    JSONObject jsonObject = new JSONObject(data);
                                    String plainText = jsonObject.optString("plainText");
                                    doBioAndSign(plainText, callback);
                                } catch (JSONException e) {
                                    callback.callback(e.getMessage());
                                    e.printStackTrace();
                                }
                                break;
                            case 2:
                                doBio(callback);
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        browserClient.registerHandler("getPlatform", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                callback.callback("Android");
            }
        });

        browserClient.registerHandler("saveString", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String key = jsonObject.optString("key");
                    String value = jsonObject.optString("value");
                    String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
                    SharedPreferenceUtils.getInstance().put(MainActivity.this, curLoginAccount + "_h5_data_" + key, value);
                    callback.callback("true");
                } catch (JSONException e) {
                    callback.callback("false");
                }
            }
        });
        browserClient.registerHandler("getString", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
                String value = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, curLoginAccount + "_h5_data_" + data, "");
                callback.callback(value);
            }
        });
        browserClient.registerHandler("checkPin", new BrowserClient.MessageHandler() {
            @Override
            public void handleMessage(String data, BrowserClient.MessageCallback callback) {
                String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
                if (curLoginAccount != null) {
                    CertManager certManager = new CertManager(MainActivity.this);
                    certManager.verifyPIN(curLoginAccount, data, new Result.ResultListener() {
                        @Override
                        public void handleResult(Result result) {
                            try {
                                JSONObject json = new JSONObject();
                                if (Result.OPERATION_SUCCEED.equals(result.getResultID())) {
                                    json.put("code", 1);
                                } else {
                                    json.put("code", 0);
                                    json.put("msg", "支付密码错误,还剩" + Integer.parseInt(result.getResultDesc()) + "次机会");
                                }
                                callback.callback(json.toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    try {
                        JSONObject json = new JSONObject();
                        json.put("code", 0);
                        json.put("msg", "获取当前用户名失败");
                        callback.callback(json.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
            ToastUtil.toast("您的系统版本过低，不支持指纹功能");
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (fingerprintManager != null) {
                if (!fingerprintManager.isHardwareDetected()) {
                    ToastUtil.toast("您的手机不支持指纹功能");
                    return false;
                } else if (keyguardManager != null) {
                    if (!keyguardManager.isKeyguardSecure()) {
                        ToastUtil.toast("您还未设置锁屏，请先设置锁屏并添加一个指纹");
                        return false;
                    } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                        ToastUtil.toast("您至少需要在系统设置中添加一个指纹");
                        return false;
                    }
                } else {
                    ToastUtil.toast("键盘管理初始化失败");
                    return false;
                }
            } else {
                ToastUtil.toast("指纹管理初始化失败");
                return false;
            }
        }
        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == RESULT_OK) {
                if (requestCode == 0) { //扫描
                    String result = data.getStringExtra("result");
                    String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");


                    QrCodeDto qrCodeDto = new QrCodeDto();
                    qrCodeDto.setQrCode(result);
                    qrCodeDto.setStatus(1);
                    qrCodeDto.setUserNo(curLoginAccount);

                    RetrofitUtils.getService().qrCodeLogin("1", "1", qrCodeDto).enqueue(new CustomCallBack<ResponseBody>() {

                        @Override
                        public void onFailure(Call call, Throwable t) {
                            super.onFailure(call, t);

                        }

                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            try {
                                if (response.body() != null) {
                                    String result = response.body().string();
                                    JSONObject jsonObject = new JSONObject(result);
                                    int code = jsonObject.getInt("code");
                                    if (code == 200) {
                                        new ScanLoginDialog(MainActivity.this, qrCodeDto)
                                                .show();
                                    } else {
                                        String msg = jsonObject.getString("msg");
                                        ToastUtil.toast(msg);
                                    }
                                } else {
                                    ResponseBody errorResponseBody = response.errorBody();
                                    if (errorResponseBody != null) {
                                        ToastUtil.toast(errorResponseBody.string());
                                    }
                                }
                            } catch (IOException | JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void doBioAndSign(String plainText, BrowserClient.MessageCallback callback) {
        new BiometricIdentifyDialog(this, new BiometricIdentifyDialog.CallBack() {
            @Override
            public void success() {
                String curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
                String pin = (String) SharedPreferenceUtils.getInstance().get(MainActivity.this, curLoginAccount, "");
                sign(1, curLoginAccount, pin, plainText, callback);
            }

            @Override
            public void onPrepared() {

            }

            @Override
            public void failure(String msg) {
                try {
                    JSONObject json = new JSONObject();
                    json.put("code", 0);
                    json.put("msg", msg);
                    callback.callback(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).show();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void doBio(BrowserClient.MessageCallback callback) {
        new BiometricIdentifyDialog(this, new BiometricIdentifyDialog.CallBack() {
            @Override
            public void success() {
                try {
                    JSONObject json = new JSONObject();
                    json.put("code", 1);
                    callback.callback(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onPrepared() {

            }

            @Override
            public void failure(String msg) {
                try {
                    JSONObject json = new JSONObject();
                    json.put("code", 0);
                    json.put("msg", msg);
                    callback.callback(json.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).show();
    }

    private void getBioState(String username, BrowserClient.MessageCallback callback) {
        RetrofitUtilsTwo.getService().doAccountIsAlive("1", "1", username)
                .enqueue(new CustomCallBack<ResponseBody>() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        super.onFailure(call, t);
                    }

                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.body() != null) {
                                String result = response.body().string();
                                JSONObject ret = new JSONObject();
                                JSONObject jsonObject = new JSONObject(result);
                                int code = jsonObject.getInt("code");
                                JSONObject data = jsonObject.optJSONObject("data");
                                if (code == 200) {
                                    String muDevices = data.optString("muDevices");
                                    if (!"null".equals(muDevices) && !TextUtils.isEmpty(muDevices)) {
                                        List<QueryDeviceInfoModel.MuDevicesDTO> muDevicesDTOS = GsonUtils.jsonToList(muDevices, QueryDeviceInfoModel.MuDevicesDTO.class);
                                        String deviceId = DeviceIdUtil.getDeviceId(MainActivity.this);
                                        ret.put("code", 1);
                                        ret.put("msg", "生物识别未开启");
                                        for (int i = 0; i < muDevicesDTOS.size(); i++) {
                                            if (muDevicesDTOS.get(i).getDeviceId().equals(deviceId)) {
                                                if (muDevicesDTOS.get(i).getFpSwitch() == 1) {         //指纹开关启用
                                                    ret.put("code", 1);
                                                    ret.remove("msg");
                                                } else {
                                                    ret.put("code", 0);
                                                    ret.put("msg", "生物识别未开启");
                                                }
                                                break;
                                            }
                                        }
                                        callback.callback(ret.toString());
                                    }
                                }
                            } else {
                                ResponseBody errorResponseBody = response.errorBody();
                                if (errorResponseBody != null) {
                                    try {
                                        JSONObject ret = new JSONObject();
                                        ret.put("code", 1);
                                        ret.put("msg", errorResponseBody.toString());
                                        callback.callback(ret.toString());
                                    } catch (JSONException jsonException) {
                                        jsonException.printStackTrace();
                                    }
                                }
                            }
                        } catch (IOException | JSONException e) {
                            try {
                                JSONObject ret = new JSONObject();
                                ret.put("code", 1);
                                ret.put("msg", e.getMessage());
                                callback.callback(ret.toString());
                            } catch (JSONException jsonException) {
                                jsonException.printStackTrace();
                            }
                        }
                    }
                });
    }


    private void getUserBaseInfo(String username, BrowserClient.MessageCallback callback) {
        RetrofitUtils.getService().getUserBaseInfo("1", "1", username)
                .enqueue(new CustomCallBack<ResponseBody>() {

                    @Override
                    public void onFailure(Call call, Throwable t) {
                        super.onFailure(call, t);

                    }

                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                        try {
                            if (response.body() != null) {
                                String result = response.body().string();
                                JSONObject jsonObject = new JSONObject(result);
                                int code = jsonObject.getInt("code");
                                if (code == 200) {
                                    String data = jsonObject.getString("data");
                                    if (!"null".equals(data) && !TextUtils.isEmpty(data)) {
                                        JSONObject dataJson = new JSONObject(data);
                                        dataJson.put("dn", "123");
                                        callback.callback(dataJson.toString());
                                    } else {
                                        ToastUtil.toast("查询在用用户基本信息为null");
                                    }
                                } else {
                                    String msg = jsonObject.getString("msg");
                                    ToastUtil.toast(msg);
                                }
                            } else {
                                ResponseBody errorResponseBody = response.errorBody();
                                if (errorResponseBody != null) {
                                    ToastUtil.toast(errorResponseBody.string());
                                }
                            }
                        } catch (IOException | JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void sign(final int which, String userName, String PIN, String plain_text, BrowserClient.MessageCallback callback) {
        SignManager signManager = new SignManager(this);
        Result.ResultListener resultListener = new Result.ResultListener() {
            @Override
            public void handleResult(Result result) {
                if (TextUtils.equals(Result.OPERATION_SUCCEED, result.getResultID())) {
                    callback.callback(result.getResultDesc());
                } else {
                    // 签名失败提示
                    Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        };
        switch (which) {
            case 0:
                signManager.sign(userName, PIN, plain_text.getBytes(), 0, resultListener);
                break;
            case 1:
                signManager.sign(userName, PIN, plain_text.getBytes(), 2, resultListener);
                break;
            case 2:
                signManager.sign(userName, PIN, plain_text.getBytes(), 1, resultListener);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        binding.webView.loadUrl("javascript:JSBridge._native_call_web('onBackPressed')");
    }

    private void clear(File dir) {
        for (String name : Objects.requireNonNull(dir.list())) {
            File file = new File(dir, name);
            if (file.isFile()) {
                file.delete();
            }
        }
    }
}

